import {
  WEATHER,
  HOME,
  homeType,
  dateInfo
} from '../../utils/api';
import {
  getNowDate
} from '../../utils/util';
const app = getApp()
let timer = null;
let topTimer = null;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    scrollTopFixed: false,
    tipshow: false, //底部提示
    imgUrl: app.globalData.imgUrl,
    wxImgUrl: app.globalData.wxImgUrl,
    weatherInfo: {
      city:'',
      airLevel: ''
    },
    city:'',
    isloading: true,
    category: '',
    searchBg: app.globalData.imgUrl + '088166997724546100010.png',
    navbar: [{
        id: 1,
        name: '急救常识',
        img: app.globalData.imgUrl + '088166997709503300008.png',
      },
      {
        id: 2,
        name: '防骗小贴士',
        img: app.globalData.imgUrl + '088166997713687200009.png',
      },
    ],
    typename: '全部分类',
    showType: false,
    subNav: [{
      id: '',
      img: 'https://6laoyou.com/api/files/category/qb@3x.png',
      name: '全部分类',
    }, ],
    current: 0,
    list: [],
    isHot: 'NO',
    isNew: 'YES',
    page: 1,
    typeName: '',
    totals: 0,
    isScroll: false,
    contentTop: 0,
    navBarHeight: '', //头高度
    statusBarHeight: '', //状态栏高度
    date: '',
		dateInfo: {},
		dateLeft: '',
		selectDate: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    homeType({index:1}).then(res => {
      this.setData({
        subNav: this.data.subNav.concat(res),
      });
    });

    //获取头部高度
    let navBarHeightinfo = app.publicFun.navBarHeightinfo()
    let _this = this
    wx.createSelectorQuery().select('.home-content').boundingClientRect(rect=> {
      if(rect){
        _this.setData({
          contentTop: rect.top - navBarHeightinfo[0]
        })
      }
    }).exec()
    _this.setData({
      navBarHeight: navBarHeightinfo[0],
      statusBarHeight: navBarHeightinfo[1]
    })
    const nowDate = getNowDate()
    this.getNowDate(nowDate);
    this.DataOnLoad()
  },
  onShow() {
    let _this = this;
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        //天气
        WEATHER({
          lat: res.latitude,
          lon: res.longitude,
        }).then(result => {
          if(result){
            _this.setData({
              weatherInfo: result,
              city:result.city.split(' ')[1]
            });
          }
        });
      },
      fail: function (errInfo) {
        console.info(errInfo);
      },
    });

    // _this.getlist();
  },
  handlerShowtype() {
    this.setData({
      showType: !this.data.showType,
    });
  },
  //分类
  handlerType(e) {
    let item = e.currentTarget.dataset.item;
    this.setData({
      category: item.id,
      showType: false,
      list: [],
      page: 1,
      typename: item.name,
      isloading: true,
    });
    this.getlist();
  },
  //获取数据
  getlist() {
    wx.showLoading({
      title: '正在加载中',
      icon: 'none',
    });
    HOME({
      pageSize: 10,
      pageNum: this.data.page,
      sortType: this.data.isNew == 'YES' ? 'recently' : 'hot',
      categoryId: this.data.category,
    }).then(res => {
      const {
        records,
        total
      } = res;
      if (this.data.page > 1) {
        this.data.list = this.data.list.concat(records);
      } else {
        this.data.list = records;
      }
      this.setData({
        list: this.data.list,
        isloading: true,
        totals: total,
      });
      wx.hideLoading({
        success: res => {},
      });
    });
  },
  //tab
  handlerTab(e) {
    let id = e.currentTarget.dataset.id;
    if (id == 0) {
      wx.navigateTo({
        url: '/inquiry/pages/index/index',
      });
    } else {
      wx.navigateTo({
        url: `/inquiry/pages/sense/index?id=${id}`,
      });
    }
  },
  handlerInfo(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `../detail/index?id=${id}`,
    });
  },
  // 回到顶部
  handleBackTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    });
  },
  //最新
  handlerHot(e) {
    let type = e.currentTarget.dataset.type;
    this.setData({
      current: type,
      list: [],
      page: 1,
      isNew: type == 1 ? 'NO' : 'YES',
      isHot: type == 0 ? 'NO' : 'YES',
      isloading: true,
    });
    this.getlist();
  },
  /*
  页面滚动
  */
  onPageScroll(e) {
    let scrollTop = e.scrollTop;
    if (scrollTop >= 500) {
      if (timer !== null) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        this.setData({
          isScroll: true,
        });
      }, 500);
    } else {
      if (topTimer !== null) {
        clearTimeout(topTimer)
      }
      topTimer = setTimeout(() => {
        this.setData({
          isScroll: false
        })
      }, 500)
    }

    if (scrollTop > this.data.contentTop) {
      this.setData({
        scrollTopFixed: true
      })
    } else {
      this.setData({
        scrollTopFixed: false
      })
    }
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isloading && this.data.list.length < this.data.totals) {
      this.data.page++;
      this.setData({
        isloading: false,
        tipshow: true,
        page: this.data.page,
      });
      this.getlist();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '光顾六个老友,健康快乐久久',
      imageUrl: this.data.wxImgUrl+'微信图片_20230416154916.jpg',
    };
  },
  getNowDate(selectedDateStr){
    // var nowtime= new Date().toISOString().substring(0, 10);
    this.setData({
      date:selectedDateStr,
      selectDate:new Date().getFullYear(),
      dateLeft:(new Date().getMonth() + 1) + '月' + new Date().getDate() + '日'
    })
  },
  bindDateChange: function (e) {
    let page = this;
    console.log(e.detail.value)
    this.setData({
      date: e.detail.value
    })
    const ymd = this.data.date;
    wx.request({
      url: 'https://apis.tianapi.com/lunar/index?key=6d385479ba78ca1fbfd20168bb069392&date=' + ymd + '',
      header: {
        'content-type': 'application/json'
      },
      success(res) {
        console.log(res.data);
        page.setData({
          //第一个data为固定用法
          list: res.data,
        })
      }
    })
    
  },

  DataOnLoad() {
    let page = this;
    // const ymd = this.data.date;
    // wx.request({
    //   url: 'https://apis.tianapi.com/lunar/index?key=6d385479ba78ca1fbfd20168bb069392&date=' + ymd + '',
    //   header: {
    //     'content-type': 'application/json'
    //   },
    //   success(res) {
    //     page.setData({
    //       //第一个data为固定用法
    //       list: res.data,
    //     })
    //   }
    // })
    const nowDate = getNowDate()
    dateInfo().then(res => {
      if(res){
        page.setData({
          //第一个data为固定用法
          dateInfo: res,
        })
      }
    })
  },
  Datejia(e) {
    var dateTime = new Date(this.data.date); //用Date对象将时间转换成中国标准时间
    console.log(dateTime)
    dateTime = new Date(dateTime.setDate(dateTime.getDate() + 1)) //Day+1
    console.log(dateTime)
    dateTime = dateTime.toJSON().substring(0, 10) //转换成yyyy-mm-dd格式
    console.log(dateTime)
    this.data.date=dateTime
    console.log(this.data.date)
    this.setData({
      date: this.data.date
    })
   this.DataOnLoad() 
  },
  Datejian(){
    var dateTime = new Date(this.data.date);//用Date对象将时间转换成中国标准时间
    dateTime = new Date(dateTime.setDate(dateTime.getDate() - 1)) //Day+1
    dateTime = dateTime.toJSON().substring(0, 10) //转换成yyyy-mm-dd格式
    this.data.date=dateTime
    this.setData({
      date: this.data.date
    })
    this.DataOnLoad() 
  },
  goQuery(e){
    console.log(e)
    const type = e.currentTarget.dataset['type']
    if(type === "1"){
      wx.navigateTo({
        url: '/pages/cosmetics/index'
      })
    }else{
      wx.navigateTo({
        url: '/pages/health-products/index'
      })
    }
    
  }
});